
package org.testfire.realm.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * This class is one way to prevent null String values from displaying as 'null' in the UI.
 *
 * @author Geoff M. Granum
 * @version 1.0
 */
public class StringConverter implements Converter {


	public StringConverter() {
	}

	/**
	 * Return the string itself, unless the string is null, in which case a new empty string
	 * is returned.
	 *
	 * @param facesContext Passed by the Application Server
	 * @param uIComponent The component which this Converter is attatched to.
	 * @param string String The string to 'convert'
	 * @return Object The string passed, or an empty String if the passed String was null.
	 * @throws ConverterException On failure to convert.
	 */
	public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String string)
			throws ConverterException {
		String s;
		if (string == null || string.equals("null")) {
			s = "";
		}
		else {
			s = string;
		}
		return s;

	}

	/**
	 * Return the string itself, unless the string is null, in which case a new empty string
	 * is returned.
	 * <p/>
	 * It can happen that the Object passed will actually be the string 'null'; this method
	 * will return an empty string in this case as well.	 *
	 *
	 * @param facesContext Passed by the Application Server
	 * @param uIComponent THe component to which this Converter is attatched.
	 * @param object The object which needs to be prevented from showing a toString value of 'null'
	 * @return String A non-null but possibly empty string.
	 * @throws ConverterException On failure to convert.
	 */
	public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object)
			throws ConverterException {
		String s;
		if (object == null || object.toString().equals("null")) {
			s = "";
		}
		else {
			s = object.toString();
		}
		return s;

	}
}
